<!--  -->
<template>
  <div class="second-div">
    <el-col :span="3">
      <div>
        <bav :numbav="$route.query.isbav"></bav>
      </div>
    </el-col>

    <el-col :span="20" :offset="1">
      <div style>
        <el-card shadow="never">
          <el-button class="el-icon-plus" type="primary" round @click="addOrUpdateTask()">&nbsp创建作业</el-button>
          <p class="tag">作业列表</p>

          <el-table :data="tableData" style="width: 100%">
            <el-table-column prop label="标题" width="180">
              <template slot-scope="scope">
                <div>
                  <div class="tag-title" v-text="scope.row.title"></div>
                  <span class="tag-1" v-if="scope.row.kind == 0">普通作业</span>
                  <span class="tag-1" v-else style="color: red">考试</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="已发布班级" width="267">
              <template slot-scope="scope">
                <div v-for="(item, index) in scope.row.kcbj" :key="index" style="float: left">
                  <span class="tag-2" v-if="item.status == 1">{{ item.name }}&nbsp&nbsp</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="handlePublish(scope.$index, scope.row)"
                  >发放</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  @click="handleManage(scope.$index, scope.row)"
                >管理</el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="handleRevise(scope.$index, scope.row)"
                >批阅</el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </el-col>
    <!-- 发布 -->
    <div>
      <el-dialog
        :close-on-click-modal="false"
        title="为班级发布作业"
        :visible.sync="publishData.ispublish"
        width="70%"
      >
        <el-table :data="publishData.kcbj" style="width: 100%">
          <el-table-column prop="name" label="班级" width="180">
          </el-table-column>
          <el-table-column label="开始时间————截止时间" width="500">
            <template slot-scope="scope">
              <el-date-picker v-model="scope.row.startTime" type="datetime" placeholder="选择开始时间"></el-date-picker>
              <el-date-picker v-model="scope.row.submitTime" type="datetime" placeholder="选择结束时间"></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#909399"
                active-text="发放"
                :active-value="1"
                :inactive-value="0"
                @change="switchChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import Selectmenus from '../selectmenus.vue';
import Bav from '../bav.vue';
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: { Selectmenus, Bav },
  data() {
    //这里存放数据
    return {
      time: '',
      publishData: {
        ispublish: false,
        taskId: '',
        kcbj: [
          {
            // id: "23",
            // name: "一班",
            // startTime: "2021-04-05 15:21:00",
            // submitTime: "",
            // status: "0",
          },
        ],
      },
      tableData: [
        // {
        //   id: "12",
        //   title: "第一次作业",
        //   ststus: "",
        //   kind: "0",
        //   createTime: "2021-10-12",
        //   kcbj: [
        //     { id: "12", name: "5班", startTime: "", submitTime: "" },
        //     { id: "", name: "6班", startTime: "", submitTime: "" },
        //   ],
        // },
      ],
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    //获取所有作业详情数据
    getTaskDetail() {
      this.$http({
        url: this.$http.adornUrl(`/edu-task/kcbjtasks/${this.$route.query.courseid}`),
        methods: 'get',
        params: this.$http.adornParams(),
      }).then((data) => {
        if (data && data.data.code === 20000) {
          this.tableData = '';
          // this.tableData = data.data.data.data;
          console.log(data.data.data.list);
          this.tableData = data.data.data.list;

          //更新页面
        } else {
          // this.$refs.slideblock.reset();
          this.$message.error('未能成功获取数据！');
        }
      });
    },
    //给班级发布作业
    handlePublish(index, row) {
      console.log('row:', row);
      this.publishData.ispublish = true;
      this.publishData.taskId = row.id;
      this.publishData.kcbj = row.kcbj;

      this.$http({
        url: this.$http.adornUrl(`/edu-kcbj/kcbj/${this.$route.query.courseid}`),
        methods: 'get',
        params: this.$http.adornParams(),
      }).then((data) => {
        if (data && data.data.code === 20000) {
          let arr = data.data.data.data;
          console.log(arr);
          // if(this.publishData.kcbj.length)
          var temp = [];
          console.log('kcbj:', this.publishData.kcbj);
          console.log('arr:', arr);

          for (let index = 0; index < arr.length; index++) {
            let index1 = 0;
            for (; index1 < this.publishData.kcbj.length; index1++) {
              if (this.publishData.kcbj[index1].id == arr[index].id) {
                break;
              }
            }
            if (index1 == this.publishData.kcbj.length) {
              temp.push({
                id: arr[index].id,
                name: arr[index].name,
                startTime: '',
                submitTime: '',
                status: 0,
              });
            }
          }
          console.log('temp', temp);
          this.publishData.kcbj = this.publishData.kcbj.concat(temp);
          // this.tableData = data.data.data.data;
          //更新页面
        } else {
          // this.$refs.slideblock.reset();
          this.$message.error('未能成功获取数据！');
        }
      });
    },
    //格林威治时间时间转化
    rTime(date) {
      var json_date = new Date(date).toJSON();
      return new Date(new Date(json_date).getTime() + 8 * 3600 * 1000)
        .toISOString()
        .replace(/T/g, ' ')
        .replace(/\.[\d]{3}Z/, '');
    },
    switchChange(row) {
      if (row.startTime != '' && row.submitTime != '' && new Date(row.startTime).getTime() < new Date(row.submitTime).getTime()) {
        this.$http({
          url: this.$http.adornUrl(`/kcbj-task/create`),
          method: 'put',
          data: this.$http.adornData(
            {
              taskId: this.publishData.taskId,
              kcbjId: row.id,
              startTime: this.rTime(row.startTime),
              submitTime: this.rTime(row.submitTime),
              status: row.status,
            },
            false
          ),
        }).then((data) => {
          if (data) {
            console.log('发布成功', data);
            this.getTaskDetail();
          } else {
            this.$message.error('此班级发布失败');
          }
        });
      } else {
        row.status = 0;
        this.$message.error('请设置时间并确保结束时间大于开始时间');
      }
    },

    //管理
    handleManage(index, row) {
      this.$router.push({
        name: 'teacheraddtask',
        query: {
          courseid: this.$route.query.courseid,
          courseName: this.$route.query.courseName,
          taskId: row.id,
        },
      });
    },
    //删除
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该该作业, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl(`/edu-task/${row.id}`),
            method: 'delete',
            params: this.$http.adornParams(),
          }).then(({ data }) => {
            if (data && data.code === 20000) {
              this.$message({
                message: '删除作业成功',
                type: 'success',
              });
              this.getTaskDetail();
            } else {
              this.$message.error('未能成功删除该作业');
            }
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    //创建或修改作业信息
    addOrUpdateTask() {
      this.$router.push({
        name: 'teacheraddtask',
        query: {
          courseid: this.$route.query.courseid,
          courseName: this.$route.query.courseName,
        },
      });
    },
    //批阅
    handleRevise(index, row) {
      //teacherrevisetask
      this.$router.push({
        name: 'teacherrevisetask',
        query: {
          courseid: this.$route.query.courseid,
          courseName: this.$route.query.courseName,
          taskId: row.id,
        },
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getTaskDetail();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.second-div {
  // width: 80%;
  margin: 0 auto;
}
.tag {
  color: #909399;
  padding: 0 10px;
  font-size: 15px;
  white-space: nowrap;
    line-height: 20px;
}
.tag-0 {
  // color: black;
  font-size: 15px;
  font-weight: 400;
  white-space: nowrap;
}
.tag-title {
  // color: black;
  font-size: 15px;
  font-weight: 400;
}
.tag-1 {
  color: #909399;
  font-size: 10px;
  white-space: nowrap;
}
.tag-2 {
  // color: black;
  font-size: 10px;
  white-space: nowrap;
}
</style>